﻿// -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	SmartLib
//  File name:	CtxStack.cs
//  Developer:	
//  Created:	20.10.2012
// 
// -------------------- iSharePoint -------------------- //

using System;
using System.Collections.Generic;
using System.Web;

namespace Smart
{
	public class CtxStack<TContextType>
		where TContextType : CtxInfo
	{
		public string Key;
		public Stack<TContextType> Stack;

		public CtxStack(string key)
		{
			Key = key;
		}

		public CtxElevator<TContextType> NewCtx(TContextType ctx)
		{
			return new CtxElevator<TContextType>(this, ctx);
		}

		public Stack<TContextType> GetCtx()
		{
			var res = Stack;

			if (res != null)
				return res;

			var ctx = HttpContext.Current;

			return
				ctx != null
					? (Stack<TContextType>)(ctx.Items[Key] ?? (ctx.Items[Key] = new Stack<TContextType>()))
					: Stack = new Stack<TContextType>();
		}

		public void PushCtx(TContextType ctx)
		{
			var stack = GetCtx();

			if ((ctx.CtxIndex = stack.Count) > 0)
				ctx.CtxPrevious = stack.Peek();

			stack.Push(ctx);
		}

		public TContextType PopCtx()
		{
			var stack = GetCtx();

			return stack.Pop();
		}

		public TContextType PeekCtx()
		{
			var stack = GetCtx();

			return
				stack.Count > 0
					? stack.Peek()
					: null;
		}

		/// <exception cref="InvalidOperationException">CtxStack.FreeCtx: incorrect order of CtxStack free!</exception>
		public void FreeCtx(int ctxIndex)
		{
			var stack = GetCtx();

			if (stack.Count != ctxIndex + 1)
				throw new InvalidOperationException("CtxStack.FreeCtx: incorrect order of CtxStack free!");

			stack.Pop();
		}
	}
}